package com.itheima.tlias84.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.tlias84.config.AliyunOssConfig;
import com.itheima.tlias84.config.OssClient;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * Oss对象上传工具类
 */
@Component//静态方法无法注入been
public class OssUtil {
    private OssUtil() {
    }

    @Resource
    AliyunOssConfig config;
    @Resource
    OssClient ossClient;

//    public static String ossUpload(MultipartFile file) {
    public  String ossUpload(MultipartFile file) throws IOException {
        //拆分文件后缀（类型）
        String filename = file.getOriginalFilename();
        String url = ossClient.upload(filename, file.getInputStream());
        return url;
    }
}
    //原本的写法
//    int index = filename.lastIndexOf(".");
//    String suffix = filename.substring(index);
//    //阿里云oss存储对象的访问路径
////        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
//    String endpoint = config.getEndpoint();
//    // 填写Bucket名称，例如examplebucket。
//    // --> 自己创建的自定义名字white-ht
////        String bucketName = "white-ht";
//    String bucketName =config.getBucketName();
//    //生成不重复id
//    String uuid = UUID.randomUUID().toString();
//    // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
////        String objectName = uuid + suffix;
//    //转移文件到阿里云
//    //创建OSSClient实例。-->1配置环境变量，2指定访问密钥
////        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);  配置环境变量
//    //创建OSSClient实例
//    OSS ossClient = new OSSClientBuilder().
////                build(endpoint, "LTAI5t9AKtSGwhkdPr19Hjdy", "TksiToiTwMViua7tEa9hPRdbbP87uM");
//        build(endpoint, config.getAccessKeyId(), config.getSecretAccessKey());
//    //创建OSSClient实例-->Bean 注入
//
//    //上传文件-->可以用LoadOssConfig和OssClient配置类代替
//        try {
////            ossClient.putObject(bucketName, objectName, file.getInputStream());
//        //返回文件路径url
////            String url = "https://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + objectName;
////            String url = config.getUrl() + objectName;
//        return url;
//    } catch (IOException e) {
//        throw new RuntimeException(e);
//    }

